package com.constant;

import com.message.constant.Host;
import com.message.notify.NotifyType;
import com.message.notify.RegisterNotifyMessage;
import com.register.RegisterInfo;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author linyu.dai
 * @project rpc
 * @description 用来保存所有连接到注册中心的channel
 * @creat 2022/11/29 09:42:58
 */
@Slf4j
public class ChannelMap {

    public static final Map<Channel, String> CHANNEL_SERVER = new ConcurrentHashMap<>();

    public static void setChannelServer(Channel channel, String serverName){
        CHANNEL_SERVER.put(channel, serverName);
    }

    /**
     * 解除注册中心 和 服务端的关联   不剃除注册表相关的信息
     */
    public static String removeChannelServer(Channel channel){
        //删除注册中心和服务之间的连接
       return CHANNEL_SERVER.remove(channel);
    }

    //通知客户端服务不可用
    public static void notifyClient(String serveName){
        log.info("{} 服务下线",serveName);
        RegisterNotifyMessage registerNotifyMessage = new RegisterNotifyMessage();
        registerNotifyMessage.setServerName(serveName);
        registerNotifyMessage.setNotifyType(NotifyType.OFFLINE);
        CHANNEL_SERVER.keySet().forEach(channel -> channel.writeAndFlush(registerNotifyMessage));
    }

    //通知服务上线
    public static void notifyClient(String serveName, Host host, Channel channel){
        log.info("{} 服务上线",serveName);
        RegisterNotifyMessage registerNotifyMessage = new RegisterNotifyMessage();
        registerNotifyMessage.setServerName(serveName);
        registerNotifyMessage.setNotifyType(NotifyType.ONLINE);
        registerNotifyMessage.setHost(host);
        //过滤掉自己
        CHANNEL_SERVER.keySet().stream().filter(channel1 -> !channel1.equals(channel)).forEach(channel1 -> channel1.writeAndFlush(registerNotifyMessage));
    }
}
